package cn.com.surker.sale.controller;

import cn.com.surker.common.AbstractController;
import cn.com.surker.common.Code;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.sale.entity.SaleClient;
import cn.com.surker.sale.entity.SaleClientOrg;
import cn.com.surker.sale.service.SaleClientOrgService;
import cn.com.surker.sale.service.SaleClientService;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.DataSourceService;
import cn.com.surker.system.service.IErpOriginService;
import cn.com.surker.util.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import cn.com.surker.spring.RestResultDto;

import javax.annotation.Resource;
import javax.transaction.RollbackException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 销售客户表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-06-18
 */

@RestController
@RequestMapping("/sale/client")
public class SaleClientController extends AbstractController {

	@Resource
	private SaleClientService saleClientService;
	@Resource
	private SaleClientOrgService saleClientOrgService;
	@Resource
	private IErpOriginService originService;
	@Resource
	private DataSourceService dataSourceService;

	/**
	 * 新增客户
	 *
	 * @param name     名称
	 * @param fullName 全称
	 * @param taxCode  税号
	 * @param linkMan  联系人
	 * @param phone    手机号
	 * @param address  地址
	 * @param email    邮箱
	 * @param orgId    站点
	 * @param type     类型
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.PUT)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class, propagation = Propagation.REQUIRED)
	public RestResultDto save(String name, String fullName, String taxCode, String linkMan, String phone, String address, String email, Long orgId, Integer type, String remark) {
		CacheUser user = getUser();
		Long userId = user.getId();
		if (orgId == null) {
			return RestResultDto.fail(Code.NO_STATION);
		}
		if (StringUtils.isBlank(fullName)) {
			//	验证供应商名称
			return RestResultDto.fail(Code.CLIENT_NAME_EMPTY);
		}
		if (!validTaxCode(taxCode, type)) {
			//	验证企业税号
			return RestResultDto.fail(Code.GROUP_TAXCODE_ERROR);
		}
		//	查询公司id
		SysOrigin origin = originService.queryById(orgId);
		if (origin == null) {
			//	未查询到公司数据
			return RestResultDto.fail(Code.STATION_ERROR);
		}
		//	根据税号或者名称查询客户信息
		SaleClient oldClient = saleClientService.queryByTaxCode(taxCode);
		if (oldClient != null) {
			//	已经存在
			return RestResultDto.fail(Code.MATERIAL_SUPPLIER_CODE_REPEAT_ADD);
		}
		oldClient = saleClientService.queryByName(name);
		if (oldClient != null) {
			return RestResultDto.fail(Code.MATERIAL_SUPPLIER_NAME_REPEAT_ADD);
		}
		Date nowDate = new Date();
		//	新增供应商数据
		SaleClient saleClient = new SaleClient(name, fullName, taxCode, linkMan, phone, address, email, type, StateEnum.ENABLED.getCode(), userId.toString(), nowDate);
		//	保存数据
		saleClientService.save(saleClient);
		//	客户id
		Long clientId = saleClient.getId();
		//	查询数据源
		DataSourceInfo ds = dataSourceService.getDataSourceByOrgId(orgId);
		//	保存关联关系
		SaleClientOrg saleClientOrg = new SaleClientOrg(clientId, orgId, origin.getOriginName(), ds.getId(), StateEnum.ENABLED.getCode(), remark, userId.toString(), nowDate);
		saleClientOrgService.save(saleClientOrg);
		return RestResultDto.success();
	}

	/**
	 * 保存关联客户的信息
	 *
	 * @param type     类型
	 * @param clientId 客户id
	 * @param orgId    站点id
	 * @param status   0启用,1禁用
	 * @param remark   备注
	 * @return
	 */
	@RequestMapping(value = "/save-relation", method = RequestMethod.PUT)
	@ResponseBody
	public RestResultDto saveRelation(Integer type, Long clientId, Long orgId, Integer status, String remark) {
		if (clientId == null || orgId == null || type == null) {
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		//	查询供应商信息
		SaleClient saleClient = saleClientService.getById(clientId);
		if (saleClient == null || !StateEnum.ENABLED.getCode().equals(saleClient.getStatus())) {
			//	供应商不存在或者被禁用
			return RestResultDto.fail(Code.ERROR_DATA);
		}
		//	查询公司id
		SysOrigin origin = originService.queryById(orgId);
		if (origin == null) {
			//	未查询到公司数据
			return RestResultDto.fail(Code.STATION_ERROR);
		}
		if (status == null) {
			//	默认启用
			status = StateEnum.ENABLED.getCode();
		}
		//	用户信息
		CacheUser user = getUser();
		Long userId = user.getId();
		Date nowDate = new Date();
		//	查询关联关系
		SaleClientOrg saleClientOrg = saleClientOrgService.queryData(clientId, orgId, type, null);
		if (saleClientOrg != null) {
			//	之前存在
			String oldRemark = saleClientOrg.getRemark();
			oldRemark += ";" + remark;
			saleClientOrg.setRemark(oldRemark);
			saleClientOrg.setStatus(status);
			saleClientOrg.setUpdater(userId.toString());
			saleClientOrg.setUpdateTime(nowDate);
		} else {
			//	不存在,新增
			DataSourceInfo ds = dataSourceService.getDataSourceByOrgId(orgId);
			saleClientOrg = new SaleClientOrg(clientId, orgId, origin.getOriginName(), ds.getId(), StateEnum.ENABLED.getCode(), remark, userId.toString(), nowDate);
			saleClientOrgService.save(saleClientOrg);
		}
		return RestResultDto.success();
	}

	/**
	 * 查询关联客户的信息
	 *
	 * @param clientId 客户id
	 **/
	@RequestMapping(value = "/relation", method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto relationClient(Long clientId) {
		if (clientId == null) {
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		List<SaleClientOrg> saleClientOrgs = saleClientOrgService.queryList(clientId, null, null, null);
		return RestResultDto.success(saleClientOrgs);
	}

	/**
	 * 查询站点下的客户信息
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/relation/origin", method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto relationOrigin(Long orgId) {
		if (orgId == null) {
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		List<SaleClient> saleClients = saleClientService.queryList(null, null, null, null, orgId, StateEnum.ENABLED.getCode());
		return RestResultDto.success(saleClients);
	}
	protected boolean validTaxCode(String code, Integer type) {
		if (StringUtils.isBlank(code)) {
			return false;
		}
		if (type == null) {
			//	默认是公司
			type = SaleClient.TAX_CODE_TYPE_COMPANY;
		}
		if (type.equals(SaleClient.TAX_CODE_TYPE_COMPANY)) {
			//	验证公司税号
			boolean b = StringUtils.validTaxCode(code);
			if (b) {
				return true;
			}
		} else {
			//	验证身份证号或者手机号
			boolean isIdCard = StringUtils.validIDCard18(code);
			if (isIdCard) {
				return true;
			} else {
				//	如果不是身份证,则验证手机号
				Boolean isPhone = StringUtils.validatorPhone(code);
				if (isPhone) {
					return true;
				}
			}
		}
		return false;
	}
}



